package com.crm.service;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.crm.dao.InventoryPpDAO;
import com.crm.po.Config;
import com.crm.po.InventoryPp;
import com.crm.util.DateEx;
import com.crm.util.ExcelEx;
import com.crm.util.MathEx;
import com.crm.util.RequestEx;
import com.crm.util.StringEx;
import com.crm.vo.Excel;

public class InventoryPpService {
	
	private static Logger logger = Logger.getLogger(InventoryPpService.class);
	
	public Map<String, Object> getInventoryPps(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from InventoryPp t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行
		
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String supplier = RequestEx.getStringTrim(request.getParameter("supplier"));
		String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
		String goods = RequestEx.getStringTrim(request.getParameter("goods"));
		String ordernumber = RequestEx.getStringTrim(request.getParameter("ordernumber"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(supplier != null && supplier.trim().length() > 0){
			Hql.append(" and t.supplier like '%");
			Hql.append(supplier);
			Hql.append("%' ");
		}
		if(linkman != null && linkman.trim().length() > 0){
			Hql.append(" and t.linkman like '%");
			Hql.append(linkman);
			Hql.append("%' ");
		}
		if(goods != null && goods.trim().length() > 0){
			Hql.append(" and t.goods like '%");
			Hql.append(goods);
			Hql.append("%' ");
		}
		if(ordernumber != null && ordernumber.trim().length() > 0){
			Hql.append(" and t.ordernumber like '%");
			Hql.append(ordernumber);
			Hql.append("%' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() == 0){
			Hql.append(" and t.senddate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '9999-12-31' ");
		}
		if(fromDate.trim().length() == 0 && toDate.trim().length() > 0){
			Hql.append(" and t.senddate BETWEEN '1970-01-01' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() > 0){
			Hql.append(" and t.senddate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		
		InventoryPpDAO dao = new InventoryPpDAO();
		String countHql = "select count(t.insid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.senddate desc, t.creattime desc  ");
	    List<InventoryPp> list = dao.inventoryPpListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    
	    return map;
	} 
	
	public int getInventoryPpsCountByTreeid(String treeid, String islive){
		StringBuffer Hql = new StringBuffer(" from InventoryPp t where 1=1 ");

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		
		InventoryPpDAO dao = new InventoryPpDAO();
		String countHql = "select count(t.insid) " + Hql.toString();
		int count = dao.getCount(countHql);
	    
	    return count;
	} 
	
	public boolean saveOrUpdateInventoryPp(HttpServletRequest request){
		try{
			
			String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
			
			String insid = RequestEx.getStringTrim(request.getParameter("insid"));
			String institution = RequestEx.getStringTrim(request.getParameter("institution"));
			Date senddate = RequestEx.getSqlDate(request.getParameter("senddate"));
			String goods = RequestEx.getStringTrim(request.getParameter("goods"));
			Double amount = RequestEx.getDouble(request.getParameter("amount"));
			String unit = RequestEx.getStringTrim(request.getParameter("unit"));
			Double price0 = RequestEx.getDouble(request.getParameter("price0"));
			Double totalprice0 = RequestEx.getDouble(request.getParameter("totalprice0"));
			Double price1 = RequestEx.getDouble(request.getParameter("price1"));
			Double totalprice1 = RequestEx.getDouble(request.getParameter("totalprice1"));
			Double grossprofit = RequestEx.getDouble(request.getParameter("grossprofit"));
			String purchaser = RequestEx.getStringTrim(request.getParameter("purchaser"));
			String ordernumber = RequestEx.getStringTrim(request.getParameter("ordernumber"));
			String user = RequestEx.getStringTrim(request.getParameter("user"));
			String supplier = RequestEx.getStringTrim(request.getParameter("supplier"));
			String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
			String tel = RequestEx.getStringTrim(request.getParameter("tel"));
			String phone = RequestEx.getStringTrim(request.getParameter("phone"));
			String email = RequestEx.getStringTrim(request.getParameter("email"));
			String address = RequestEx.getStringTrim(request.getParameter("address"));
			String remark = RequestEx.getStringTrim(request.getParameter("remark"));
			Integer sort = RequestEx.getInteger(request.getParameter("sort"));
			
			InventoryPpDAO dao = new InventoryPpDAO();
			InventoryPp invPp = null;
			if(insid != null && insid.trim().length() > 0){
				invPp = dao.findById(insid);
				
			}else{				
				invPp = new InventoryPp();
				invPp.setCreattime(DateEx.getCurDatetimeAsLong());
				invPp.setCreater(RequestEx.getCurUser(request).getUsername());
			}
			
			invPp.setInstitution(institution);
			invPp.setSenddate(senddate);
			invPp.setGoods(goods);
			invPp.setAmount(amount);
			invPp.setUnit(unit);
			
			invPp.setPrice0(price0);
			invPp.setTotalprice0(totalprice0);
			invPp.setPrice1(price1);
			invPp.setTotalprice1(totalprice1);
			
			invPp.setGrossprofit(grossprofit);
			invPp.setPurchaser(purchaser);
			invPp.setOrdernumber(ordernumber);
			invPp.setUser(user);
			invPp.setSupplier(supplier);
			invPp.setLinkman(linkman);
			invPp.setTel(tel);
			invPp.setPhone(phone);
			invPp.setEmail(email);
			invPp.setAddress(address);
			invPp.setCGroup(treeid);
			invPp.setSort(sort);
			invPp.setRemark(remark);
			invPp.setIslive("Y");
			
			invPp.setUpdatetime(DateEx.getCurDatetimeAsLong());
			invPp.setUpdater(RequestEx.getCurUser(request).getUsername());
			
			dao.saveOrUpdate(invPp);
		}catch(Exception e){
			logger.error("save or update inventoryPp fail:", e);
			return false;
		}
	    return true;
	}
	
	public boolean updateDdnumber(HttpServletRequest request){
		int result = 0;
		try{
			String insids = RequestEx.getStringTrim(request.getParameter("insids"));
			String newDdnumber = RequestEx.getStringTrim(request.getParameter("newDdnumber"));
			if(insids.length() > 0){
				String hql = "UPDATE InventoryPp T SET T.ordernumber = '" + newDdnumber + "' WHERE T.insid IN (" + insids + ")";
				InventoryPpDAO dao = new InventoryPpDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete inventory fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean deleteInventoryPps(HttpServletRequest request){
		int result = 0;
		try{
			String insids = RequestEx.getStringTrim(request.getParameter("insids"));
			if(insids.length() > 0){
				String hql = "UPDATE InventoryPp T SET T.islive = 'N' WHERE T.insid IN (" + insids + ")";
				InventoryPpDAO dao = new InventoryPpDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete inventoryPp fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean recoverInventoryPps(HttpServletRequest request){
		int result = 0;
		try{
			String insids = RequestEx.getStringTrim(request.getParameter("insids"));
			if(insids.length() > 0){
				String hql = "UPDATE InventoryPp T SET T.islive = 'Y' WHERE T.insid IN (" + insids + ")";
				InventoryPpDAO dao = new InventoryPpDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("recover inventoryPp fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean reallyDeleteInventoryPps(HttpServletRequest request){
		int result = 0;
		try{
			String insids = RequestEx.getStringTrim(request.getParameter("insids"));
			if(insids.length() > 0){
				String hql = "DELETE FROM InventoryPp T WHERE T.insid IN (" + insids + ")";
				InventoryPpDAO dao = new InventoryPpDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("really delete inventoryPp fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public Config getConfig(HttpServletRequest request){
		Config config = null;
		try{
			String key = RequestEx.getStringTrim(request.getParameter("key"));
			if(key.length() > 0){
				String hql = "from Config T WHERE T.CKey = '" + key + "'";
				InventoryPpDAO dao = new InventoryPpDAO();
				Object obj = dao.getUniqueResult(hql);
				if(obj != null){
					config = (Config) obj;
				}
			}			
		}catch(Exception e){
			logger.error("select config fail:", e);
			return null;
		}
	    return config;
	}
	
	public Config getConfigTaxrate(String key){
		Config config = null;
		try{
			if(key.length() > 0){
				String hql = "from Config T WHERE T.CKey = '" + key + "'";
				InventoryPpDAO dao = new InventoryPpDAO();
				Object obj = dao.getUniqueResult(hql);
				if(obj != null){
					config = (Config) obj;
				}
			}			
		}catch(Exception e){
			logger.error("select taxrate fail:", e);
			return null;
		}
	    return config;
	}
	
	public boolean exeSystemConfig(HttpServletRequest request){
		int result = 0;
		try{
			String key = RequestEx.getStringTrim(request.getParameter("key"));
			String taxrate = RequestEx.getStringTrim(request.getParameter("taxrate"));
			if(key.length() > 0){
				String hql = "UPDATE Config T SET T.CValue = '" + taxrate + "' where T.CKey = '" + key + "'";
				InventoryPpDAO dao = new InventoryPpDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("update config fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public double mathJJCC(HttpServletRequest request){
		int type = RequestEx.getInteger(request.getParameter("type"));
		Double number1 = RequestEx.getDouble(request.getParameter("n1"));
		Double number2 = RequestEx.getDouble(request.getParameter("n2"));
		
		return MathEx.mathJJCC(number1, number2, 2, type);
	}
	
	public String mathBatchAdd(HttpServletRequest request){			
		String amount_temp = RequestEx.getStringTrim(request.getParameter("amount_temp"));
		
		String price0_temp = RequestEx.getStringTrim(request.getParameter("price0_temp"));
		String totalprice0_temp = RequestEx.getStringTrim(request.getParameter("totalprice0_temp"));
		String price1_temp = RequestEx.getStringTrim(request.getParameter("price1_temp"));
		String totalprice1_temp = RequestEx.getStringTrim(request.getParameter("totalprice1_temp"));
		
		String grossprofit_temp = RequestEx.getStringTrim(request.getParameter("grossprofit_temp"));
		
		double amount_sum = MathEx.mathBatchAdd(amount_temp.split("_"), 2);
		
		double price0_sum = MathEx.mathBatchAdd(price0_temp.split("_"), 2);
		double totalprice0_sum = MathEx.mathBatchAdd(totalprice0_temp.split("_"), 2);
		double price1_sum = MathEx.mathBatchAdd(price1_temp.split("_"), 2);
		double totalprice1_sum = MathEx.mathBatchAdd(totalprice1_temp.split("_"), 2);
		
		double grossprofit_sum = MathEx.mathBatchAdd(grossprofit_temp.split("_"), 2);
		
		StringBuffer buffer = new StringBuffer("");
		
		buffer.append("{\"amount_sum\":\"" + amount_sum + "\",");
		buffer.append("\"price0_sum\":\"" + price0_sum + "\",");
		buffer.append("\"totalprice0_sum\":\"" + totalprice0_sum + "\",");
		buffer.append("\"price1_sum\":\"" + price1_sum + "\",");
		buffer.append("\"totalprice1_sum\":\"" + totalprice1_sum + "\",");
		buffer.append("\"grossprofit_sum\":\"" + grossprofit_sum + "\"}");

		return buffer.toString();
	}


	public void exportInventoryPps(HttpServletRequest request, HttpServletResponse response){
		StringBuffer Hql = new StringBuffer(" from InventoryPp t where 1=1 ");
		
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String insids = RequestEx.getStringTrim(request.getParameter("insids"));
		String supplier = RequestEx.getStringTrim(request.getParameter("supplier"));
		String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
		String goods = RequestEx.getStringTrim(request.getParameter("goods"));
		String ordernumber = RequestEx.getStringTrim(request.getParameter("ordernumber"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.CGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(insids != null && insids.trim().length() > 0){
			Hql.append(" and t.insid in (");
			Hql.append(insids);
			Hql.append(") ");
		}
		if(supplier != null && supplier.trim().length() > 0){
			Hql.append(" and t.supplier like '%");
			Hql.append(supplier);
			Hql.append("%' ");
		}
		if(linkman != null && linkman.trim().length() > 0){
			Hql.append(" and t.linkman like '%");
			Hql.append(linkman);
			Hql.append("%' ");
		}
		if(goods != null && goods.trim().length() > 0){
			Hql.append(" and t.goods like '%");
			Hql.append(goods);
			Hql.append("%' ");
		}
		if(ordernumber != null && ordernumber.trim().length() > 0){
			Hql.append(" and t.ordernumber like '%");
			Hql.append(ordernumber);
			Hql.append("%' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() == 0){
			Hql.append(" and t.senddate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '9999-12-31' ");
		}
		if(fromDate.trim().length() == 0 && toDate.trim().length() > 0){
			Hql.append(" and t.senddate BETWEEN '1970-01-01' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		if(fromDate.trim().length() > 0 && toDate.trim().length() > 0){
			Hql.append(" and t.senddate BETWEEN '");
			Hql.append(fromDate);
			Hql.append("' AND '");
			Hql.append(toDate);
			Hql.append("' ");
		}
		
		InventoryPpDAO dao = new InventoryPpDAO();
		Hql.append(" order by t.senddate desc ");
	    List<InventoryPp> list = dao.inventoryPpList(Hql.toString());
	    
	    String[][] grids = new String[list.size() + 1][22];
	    String[] titles = {"公司名称", "送货日期 ", "采购物品 ", "数量 ", "单位", "采购单价", "采购合计金额", 
	    				   "销售单价", "销售合计金额", "毛利润", "采购人", "订单号", "使用人", "供应商", 
	    				   "联系人", "固定电话", "移动电话", "电子邮箱", "地址", "备注", "创建时间", "修改时间"}; 
	    grids[0] = titles;
		for(int i = 0; i < list.size(); i ++){
			InventoryPp invPp = list.get(i);
			
			grids[i + 1][0] = StringEx.valueOf(invPp.getInstitution());
			grids[i + 1][1] = StringEx.valueOf(invPp.getSenddate(), StringEx.formatDate);
			grids[i + 1][2] = StringEx.valueOf(invPp.getGoods());
			grids[i + 1][3] = StringEx.valueOf(invPp.getAmount());
			grids[i + 1][4] = StringEx.valueOf(invPp.getUnit());
			
			grids[i + 1][5] = StringEx.valueOf(invPp.getPrice0());
			grids[i + 1][6] = StringEx.valueOf(invPp.getTotalprice0());
			grids[i + 1][7] = StringEx.valueOf(invPp.getPrice1());
			grids[i + 1][8] = StringEx.valueOf(invPp.getTotalprice1());

			grids[i + 1][9] = StringEx.valueOf(invPp.getGrossprofit());
			grids[i + 1][10] = StringEx.valueOf(invPp.getPurchaser());
			grids[i + 1][11] = StringEx.valueOf(invPp.getOrdernumber());
			grids[i + 1][12] = StringEx.valueOf(invPp.getUser());
			grids[i + 1][13] = StringEx.valueOf(invPp.getSupplier());
			grids[i + 1][14] = StringEx.valueOf(invPp.getLinkman());
			grids[i + 1][15] = StringEx.valueOf(invPp.getTel());
			grids[i + 1][16] = StringEx.valueOf(invPp.getPhone());
			grids[i + 1][17] = StringEx.valueOf(invPp.getEmail());
			grids[i + 1][18] = StringEx.valueOf(invPp.getAddress());
			grids[i + 1][19] = StringEx.valueOf(invPp.getRemark());
			grids[i + 1][20] = StringEx.valueOfLongDate(invPp.getCreattime());
			grids[i + 1][21] = StringEx.valueOfLongDate(invPp.getUpdatetime());
		}
	    ExcelEx.toExcel(request, response, new Excel("普票信息[导出时间" + DateEx.getCurDateTime() + "]", grids));
	} 
	
	public static void main(String[] args){

	}
	
}
